﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Elastic.Clients.Elasticsearch;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 球队球员申请表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppTeamPlayerApplyService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppTeamPlayerApply> _appTeamPlayerApplyRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly UserManager _userManager;

    public AppTeamPlayerApplyService(SqlSugarRepository<AppTeamPlayerApply> appTeamPlayerApplyRep, ISqlSugarClient sqlSugarClient,
        UserManager userManager)
    {
        _appTeamPlayerApplyRep = appTeamPlayerApplyRep;
        _sqlSugarClient = sqlSugarClient;
        _userManager = userManager;
    }

    /// <summary>
    /// 分页查询球队球员申请表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询球队球员申请表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppTeamPlayerApplyOutput>> Page(PageAppTeamPlayerApplyInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appTeamPlayerApplyRep.AsQueryable()
            .WhereIF((!_userManager.SuperAdmin||_userManager.SysAdmin) &&input.Type == TeamPlayerEnum.Team, u =>u.UserId==_userManager.UserId && input.Type == u.Type)
            .WhereIF((!_userManager.SuperAdmin || _userManager.SysAdmin) && input.Type == TeamPlayerEnum.Player, u => u.UserId == _userManager.UserId && input.Type == u.Type)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.Type.HasValue, u => u.Type == input.Type)
            .WhereIF(input.UserId != null, u => u.UserId == input.UserId)
            .WhereIF(input.TeamId != null, u => u.TeamId == input.TeamId)
            .WhereIF(input.Status.HasValue, u => u.Status == input.Status)
            .WhereIF(input.ApplicationDateRange?.Length == 2, u => u.ApplicationDate >= input.ApplicationDateRange[0] && u.ApplicationDate <= input.ApplicationDateRange[1])
            .WhereIF(input.ProcessedDateRange?.Length == 2, u => u.ProcessedDate >= input.ProcessedDateRange[0] && u.ProcessedDate <= input.ProcessedDateRange[1])
            .WhereIF(input.ProcessedBy != null, u => u.ProcessedBy == input.ProcessedBy)
            .LeftJoin<SysUser>((u, user) => u.UserId == user.Id)
            .LeftJoin<AppTeam>((u, user, team) => u.TeamId == team.Id)
            .LeftJoin<SysUser>((u, user, team, processedBy) => u.ProcessedBy == processedBy.Id)
            .Select((u, user, team, processedBy) => new AppTeamPlayerApplyOutput
            {
                Id = u.Id,
                Type = u.Type,
                UserId = u.UserId,
                UserFkDisplayName = $"{user.RealName}",
                TeamId = u.TeamId,
                TeamFkDisplayName = $"{team.Name}",
                Status = u.Status,
                ApplicationDate = u.ApplicationDate,
                ProcessedDate = u.ProcessedDate,
                ProcessedBy = u.ProcessedBy,
                ProcessedByFkDisplayName = $"{processedBy.RealName}",
                Remark = u.Remark,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取球队球员申请表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取球队球员申请表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppTeamPlayerApply> Detail([FromQuery] QueryByIdAppTeamPlayerApplyInput input)
    {
        return await _appTeamPlayerApplyRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加球队球员申请表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加球队球员申请表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppTeamPlayerApplyInput input)
    {
        var entity = input.Adapt<AppTeamPlayerApply>();
        return await _appTeamPlayerApplyRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新球队球员申请表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新球队球员申请表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppTeamPlayerApplyInput input)
    {
        var entity = input.Adapt<AppTeamPlayerApply>();
        await _appTeamPlayerApplyRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除球队球员申请表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除球队球员申请表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppTeamPlayerApplyInput input)
    {
        var entity = await _appTeamPlayerApplyRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appTeamPlayerApplyRep.FakeDeleteAsync(entity);   //假删除
        //await _appTeamPlayerApplyRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 设置球队管理状态 🚫
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("设置球队管理状态")]
    [ApiDescriptionSettings(Name = "SetStatus"), HttpPost]
    public async Task SetAppTeamPlayerApplyStatus(SeeAppTeamPlayerApplyInput input)
    {
        var entity = await _appTeamPlayerApplyRep.GetFirstAsync(u => u.Id == input.Id);
        if (entity != null)
        {
            if (entity.Type== TeamPlayerEnum.Team)
            {
                if (input.Status == ApplicationStatusEnum.Approved)
                {
                  await _appTeamPlayerApplyRep.ChangeRepository<SqlSugarRepository<AppTeam>>().AsUpdateable().SetColumns(u => u.Status, StatusEnum.Enable).Where(u => u.Id == entity.TeamId).ExecuteCommandAsync();
                }
                else if (input.Status == ApplicationStatusEnum.Rejected)
                {
                    await _appTeamPlayerApplyRep.ChangeRepository<SqlSugarRepository<AppTeam>>().AsUpdateable().SetColumns(u => u.Status, StatusEnum.Disable).Where(u => u.Id == entity.TeamId).ExecuteCommandAsync();
                }
            }
            else if (entity.Type == TeamPlayerEnum.Player)
            {
                if (input.Status == ApplicationStatusEnum.Approved)
                {
                    await _appTeamPlayerApplyRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().AsUpdateable().SetColumns(u => u.Status, StatusEnum.Enable).Where(u => u.TeamId == entity.TeamId && u.UserId==entity.UserId).ExecuteCommandAsync();
                }
                else if (input.Status == ApplicationStatusEnum.Rejected)
                {
                    await _appTeamPlayerApplyRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().AsUpdateable().SetColumns(u => u.Status, StatusEnum.Disable).Where(u => u.TeamId == entity.TeamId && u.UserId == entity.UserId).ExecuteCommandAsync();
                }
            }
        }

        await _appTeamPlayerApplyRep.AsUpdateable().SetColumns(u => u.Status, input.Status).SetColumns(u => u.ProcessedBy,_userManager.UserId).Where(u => u.Id == input.Id).ExecuteCommandAsync();
    }

    /// <summary>
    /// 批量删除球队球员申请表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除球队球员申请表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteAppTeamPlayerApplyInput> input)
    {
        var exp = Expressionable.Create<AppTeamPlayerApply>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appTeamPlayerApplyRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _appTeamPlayerApplyRep.FakeDeleteAsync(list);   //假删除
        //return await _appTeamPlayerApplyRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppTeamPlayerApplyInput input)
    {
        var userIdData = await _appTeamPlayerApplyRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppTeamPlayerApply>(input.FromPage, (u, r) => u.Id == r.UserId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        var teamIdData = await _appTeamPlayerApplyRep.Context.Queryable<AppTeam>()
            .InnerJoinIF<AppTeamPlayerApply>(input.FromPage, (u, r) => u.Id == r.TeamId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.Name}"
            }).ToListAsync();
        var processedByData = await _appTeamPlayerApplyRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppTeamPlayerApply>(input.FromPage, (u, r) => u.Id == r.ProcessedBy)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "userId", userIdData },
            { "teamId", teamIdData },
            { "processedBy", processedByData },
        };
    }
    
    /// <summary>
    /// 导出球队球员申请表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出球队球员申请表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppTeamPlayerApplyInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppTeamPlayerApplyOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "球队球员申请表导出记录");
    }
    
    /// <summary>
    /// 下载球队球员申请表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载球队球员申请表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppTeamPlayerApplyOutput>(), "球队球员申请表导入模板", (_, info) =>
        {
            if (nameof(ExportAppTeamPlayerApplyOutput.UserFkDisplayName) == info.Name) return _appTeamPlayerApplyRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            if (nameof(ExportAppTeamPlayerApplyOutput.TeamFkDisplayName) == info.Name) return _appTeamPlayerApplyRep.Context.Queryable<AppTeam>().Select(u => $"{u.Name}").Distinct().ToList();
            if (nameof(ExportAppTeamPlayerApplyOutput.ProcessedByFkDisplayName) == info.Name) return _appTeamPlayerApplyRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入球队球员申请表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入球队球员申请表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppTeamPlayerApplyInput, AppTeamPlayerApply>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 球员Id
                    var userIdLabelList = pageItems.Where(x => x.UserFkDisplayName != null).Select(x => x.UserFkDisplayName).Distinct().ToList();
                    if (userIdLabelList.Any()) {
                        var userIdLinkMap = _appTeamPlayerApplyRep.Context.Queryable<SysUser>().Where(u => userIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.UserId = userIdLinkMap.GetValueOrDefault(e.UserFkDisplayName ?? "");
                            if (e.UserId == null) e.Error = "球员Id链接失败";
                        });
                    }
                    // 链接 球队Id
                    var teamIdLabelList = pageItems.Where(x => x.TeamFkDisplayName != null).Select(x => x.TeamFkDisplayName).Distinct().ToList();
                    if (teamIdLabelList.Any()) {
                        var teamIdLinkMap = _appTeamPlayerApplyRep.Context.Queryable<AppTeam>().Where(u => teamIdLabelList.Contains($"{u.Name}")).ToList().ToDictionary(u => $"{u.Name}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.TeamId = teamIdLinkMap.GetValueOrDefault(e.TeamFkDisplayName ?? "");
                            if (e.TeamId == null) e.Error = "球队Id链接失败";
                        });
                    }
                    // 链接 处理人Id
                    var processedByLabelList = pageItems.Where(x => x.ProcessedByFkDisplayName != null).Select(x => x.ProcessedByFkDisplayName).Distinct().ToList();
                    if (processedByLabelList.Any()) {
                        var processedByLinkMap = _appTeamPlayerApplyRep.Context.Queryable<SysUser>().Where(u => processedByLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ProcessedBy = processedByLinkMap.GetValueOrDefault(e.ProcessedByFkDisplayName ?? "");
                            if (e.ProcessedBy == null) e.Error = "处理人Id链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Type == null){
                            x.Error = "球员申请/球队申请不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.UserId == null){
                            x.Error = "球员Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.TeamId == null){
                            x.Error = "球队Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Status == null){
                            x.Error = "申请状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppTeamPlayerApply>>();
                    
                    var storageable = _appTeamPlayerApplyRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.Remark?.Length > 256, "备注长度不能超过256个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
